//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package main

import (
	"context"
	"fmt"
	"time"

	"atomgit.com/openlinksaas-org/api-server/config"
	"atomgit.com/openlinksaas-org/api-server/dao"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/cobra"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var cfgFilePath string
var globalServCfg *config.ServerConfig

func connMongoDb(dbUrl, dbName string) (*mongo.Database, error) {
	clientOpts := options.Client().ApplyURI(dbUrl).SetConnectTimeout(10 * time.Second)
	client, err := mongo.Connect(context.Background(), clientOpts)
	if err != nil {
		return nil, err
	}
	return client.Database(dbName), nil
}

func InitConfig() error {
	servCfg, err := config.ReadConfig(cfgFilePath)
	if err != nil {
		return err
	}
	globalServCfg = servCfg
	mongoDb, err := connMongoDb(servCfg.DataBase.Mongo.Url, servCfg.DataBase.Mongo.DataBase)
	if err != nil {
		return err
	}
	rdb := redis.NewClient(&redis.Options{
		Addr:     servCfg.DataBase.Redis.Addr,
		Password: servCfg.DataBase.Redis.PassWord,
	})
	err = dao.InitDao(mongoDb, rdb)
	if err != nil {
		return err
	}
	return nil
}

func main() {
	rootCmd := &cobra.Command{}
	rootCmd.PersistentFlags().StringVar(&cfgFilePath, "config", "", "config file path")
	rootCmd.MarkPersistentFlagRequired("config")

	rootCmd.AddCommand(DumpCmd)

	err := rootCmd.Execute()
	if err != nil {
		fmt.Println(err)
	}
}
